﻿namespace ClassyBlog.Infrastructure.Specs.Unit
{
    using System;
    using System.Linq;
    using System.Web.Mvc;

    using Machine.Specifications;
    using NSubstitute;

    using Infrastructure;

    [Subject(typeof(GlobalFilterRegistrations))]
    public class when_creating_global_filter_registration_with_null_filters
    {
        static Exception exception;

        Because of = () => exception =
            Catch.Exception(() => new GlobalFilterRegistrations(null));

        It should_throw_exception = () =>
            exception.ShouldBeOfType<ArgumentNullException>();
    }

    [Subject(typeof(GlobalFilterRegistrations))]
    public class when_global_filters_are_registered
    {
        static IDependencyResolver previousDependencyResolver;
        static IDependencyResolver dependencyResolver;

        static GlobalFilterCollection filters;

        Establish context = () =>
        {
            previousDependencyResolver = DependencyResolver.Current;
            dependencyResolver = Substitute.For<IDependencyResolver>();

            dependencyResolver.GetService(
                typeof(CurrentBlog)).
                Returns(new CurrentBlog(
                    Substitute.For<ICurrentBlogProvider>()));

            DependencyResolver.SetResolver(dependencyResolver);

            filters = new GlobalFilterCollection();
        };

        Because of = () => new GlobalFilterRegistrations(filters).Register();

        It should_register_handle_error = () =>
            filters.ElementAt(0)
                   .Instance
                   .ShouldBeOfType<HandleErrorAttribute>();

        It should_register_current_blog = () =>
            filters.ElementAt(1).Instance.ShouldBeOfType<CurrentBlog>();

        Cleanup on_exit = () =>
            DependencyResolver.SetResolver(previousDependencyResolver);
    }
}